package com.wanggsx.library.util;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;

import java.util.List;

public class UtilsRecyclerView {

    /** 恢复recyclerView的位置状态 */
    public static void resetRecyclerViewPosition(int[] pos,RecyclerView recyclerView){
        //重新设置RecyclerView的位置
        ((LinearLayoutManager)recyclerView.getLayoutManager()).scrollToPositionWithOffset(pos[0],pos[1]);
        recyclerView.getAdapter().notifyDataSetChanged();
    }

    /** 记录recyclerView的位置状态 */
    public static int[] getRecyclerViewLastPosition(RecyclerView recyclerView, List listdata, LinearLayoutManager layoutManager) {
        int[] pos = new int[2];
        pos[0] = layoutManager.findFirstCompletelyVisibleItemPosition();
        OrientationHelper orientationHelper = OrientationHelper.createOrientationHelper(layoutManager, OrientationHelper.VERTICAL);
        int fromIndex = 0;
        int toIndex = listdata.size();
        final int start = orientationHelper.getStartAfterPadding();
        final int end = orientationHelper.getEndAfterPadding();
        final int next = toIndex > fromIndex ? 1 : -1;
        for (int i = fromIndex; i != toIndex; i += next) {
            final View child = recyclerView.getChildAt(i);
            final int childStart = orientationHelper.getDecoratedStart(child);
            final int childEnd = orientationHelper.getDecoratedEnd(child);
            if (childStart < end && childEnd > start) {
                if (childStart >= start && childEnd <= end) {
                    pos[1] = childStart;
                    return pos;
                }
            }
        }
        return pos;
    }

}
